import { GlobalData } from '/store/state'
import { $event } from '/utils'
import { checkAuth } from '/store/actions'
import { userApi } from '/api/user'
import { feedApi } from '/api/feed'
import { getServer } from '/store/mutations'
// import { getServer } from '/store/mutations'
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
//@ts-ignore
import getMessage from 'ts-msg-handler'
Page({
  data: {
    navigationHeight: 0,
    access: GlobalData.access,
    title: '' as string,
    list: [] as any,
    //1打赏,2赞,3评论
    id: Number,
    reward: [] as any,
    keyboardOffsetTop: 0,
    feedId: 0,
    pid: 0,
    reply_id: 0,
    inputPlaceholder: '',
    show: false,
    noMore: false,
    page: 1,
    type: '',
    isLastPage: false,
    replyUser: {} as any,
    currentTab: 0,
    navData: [{ isLastPage: false }, { isLastPage: false }],
    lists: [[] as any[]],
    number: 0,
  },
  onLoad(query: any) {
    //1打赏,2赞,3评论
    this.setData({
      id: query.id,
      title: +query.id === 1 ? '打赏消息' : +query.id === 2 ? '收到的赞' : '收到的评论',
      type: +query.id === 1 ? 'reward' : +query.id === 2 ? 'like' : 'comment',
      number: +query.number,
    })
    //消除小红点
    if (query.number > 0) {
      userApi.removeUnreadTips(this.data.type).then(() => {
        $event.emit('after:notification')
      })
    }
    wx.startPullDownRefresh()
  },
  onShow() {
    $event.on('after:boot', this, () => {
      this.setData!({
        navigationHeight: GlobalData.navigationHeight,
      })
    })
    this.setData!({
      navigationHeight: GlobalData.navigationHeight,
    })
  },
  async onPullDownRefresh() {
    if (+this.data.id === 3) {
      this.setData({
        navData: [{ isLastPage: false }, { isLastPage: false }],
        lists: [[] as any[]],
        page: 1,
      })
      await this.getLists()
    } else {
      this.setData({ page: 1 })
      await this.getList()
    }
    wx.stopPullDownRefresh()
  },
  async getList() {
    if (+this.data.id === 3) {
      return this.getLists()
    }
    const list = await userApi.getUserNewsDetail({ type: this.data.type, page: this.data.page })
    this.setData({
      list: list.data,
      page: list.meta.current_page,
      isLastPage: list.meta.current_page === list.meta.last_page,
    })
  },
  /** 如果是回答和评论 */
  async getLists(isLoadMore = false) {
    const {
      data: { currentTab: cur, lists, navData },
    } = this
    if (navData[cur].isLastPage) {
      wx.showToast({
        title: '没有更多了',
        icon: 'none',
      })
      return
    }
    const user = wx.getStorageSync(`${getServer()}/logged`).data || {}
    const { id }: { id: number } = user
    const isCommentList = +cur === 0
    let data
    // type
    if (isCommentList) {
      data = await userApi.getUserNewsDetail({
        type: this.data.type,
        for_user: id,
        page: isLoadMore ? this.data.page + 1 : 1,
        limit: 15,
      })
      this.setData({
        [`lists[${cur}]`]: isLoadMore ? [...lists[cur], ...data.data] : data.data,
        page: data.meta.current_page,
        [`navData[${cur}].isLastPage`]: data.meta.current_page === data.meta.last_page,
      })
    } else {
      data = await userApi.getUserNewsDetail({
        type: 'answer',
        for_user: id,
        offset: lists[cur] ? lists[cur].length : 0,
        limit: 15,
      })
      const list = data
      this.setData({
        [`lists[${cur}]`]: isLoadMore ? [...lists[cur], ...list] : list,
        [`navData[${cur}].isLastPage`]: list.length < 15,
      })
    }
  },
  /** 切换导航栏 */
  clickTab(e: WechatMiniprogram.BaseEvent) {
    const index = e.currentTarget.dataset.current
    const {
      data: { navData, currentTab, number, lists },
    } = this
    if (+index === +currentTab) return
    this.setData({
      currentTab: +index,
    })
    if (navData[index].isLastPage) return
    this.getLists()
    if (number > 0 && !lists[index]) {
      userApi.removeUnreadTips('answer')
    }
  },
  async onReachBottom() {
    if (+this.data.id === 3) {
      return this.getLists(true)
    }
    if (this.data.isLastPage) return
    wx.showLoading({ title: '加载中' })
    const list = await userApi.getUserNewsDetail({ type: this.data.type, page: this.data.page + 1 })
    this.setData({
      list: [...this.data.list, ...list.data],
      page: list.meta.current_page,
      isLastPage: list.meta.current_page === list.meta.last_page,
    })
    wx.hideLoading()
  },
  async toTopic(e: WechatMiniprogram.CustomEvent) {
    if (+this.data.id == 1) {
      wx.navigateTo({ url: `/pages/topic/detail/detail?topicId=${e.currentTarget.dataset.id}` })
    } else if (+this.data.id == 2) {
      //赞
      wx.navigateTo({
        url: `/pages/feed/detail/detail?feedId=${e.currentTarget.dataset.id}`,
      })
    } else {
      if (+this.data.currentTab === 1) {
        wx.navigateTo({
          url: `/pages/feed/detail/detail?feedId=${e.currentTarget.dataset.id}`,
        })
      }
      //评论
      await checkAuth()
      console.log(e)
      let mPid = 0

      if (e.currentTarget.dataset.comment.pid == 0) {
        // 一级评论的评论
        mPid = e.currentTarget.dataset.comment.id
      } else {
        // 二级评论的回复
        mPid = e.currentTarget.dataset.comment.pid
      }
      const mReplyId = e.currentTarget.dataset.comment.id
      this.setData({
        feedId: e.currentTarget.dataset.id,
        pid: mPid,
        reply_id: mReplyId,
        inputFocus: true,
        replyUser: e.currentTarget.dataset.user,
        inputPlaceholder: `回复 ${e.currentTarget.dataset.user.name}: `,
        show: true,
      })
    }
  },
  toWendas(e: WechatMiniprogram.CustomEvent) {
    return wx.navigateTo({
      url: `/index/knowAboutDetail/knowAboutDetail?id=${e.currentTarget.dataset.wendaid}`,
    })
  },
  async onInputFocus(event: WechatMiniprogram.TouchEvent) {
    const { height } = event.detail
    this.setData({
      keyboardOffsetTop: height,
    })
  },
  onInputBlur() {
    this.setData({
      show: false,
      keyboardOffsetTop: 0,
      inputFocus: false,
    })
  },
  onInputComment({ detail = {} }: any, targetValue: string) {
    const value = detail.value
    return {
      value: targetValue || value,
      pos: detail.cursor || 0,
    }
  },
  async onConfirmComment({ detail }: any) {
    const payload: PostCommentBody = { body: detail.value }
    payload.reply_user = this.data.replyUser.id
    payload.pid = this.data.pid
    payload.reply_id = this.data.reply_id
    try {
      const { amount } = await feedApi.postFeedComment(this.data.feedId, payload)
      if (amount) {
        $event.emit('showMessage', {
          message: '评论成功',
          amount: amount,
        } as GetRewardMessageReturns)
      } else {
        wx.showToast({
          title: '评论成功',
          icon: 'success',
          duration: 2000,
        })
      }
      $event.emit('after:comment')
      this.setData({
        inputFocus: false,
        show: false,
        inputValue: '',
        replyUser: null as any as DomoUser,
      })
    } catch (error) {
      wx.showToast({ title: `${getMessage(error.data).getMessage()}`, icon: 'none' })
    }
  },
  /** 跳转动态详情 */
  toFeed(e: WechatMiniprogram.CustomEvent) {
    const {
      currentTarget: {
        dataset: { id },
      },
    } = e
    return wx.navigateTo({
      url: `/pages/feed/detail/detail?id=${id}`,
    })
  },
})
